<template>
  <div class="guild-diplomacy-manage">
    <h2>公会外交关系管理</h2>

    <!-- 加载状态 -->
    <el-skeleton :loading="loading" animated v-if="!diplomacies.length && totalRecords === 0"></el-skeleton>

    <el-table :data="diplomacies" style="width: 100%" border v-else>
      <el-table-column prop="id" label="ID" align="center"></el-table-column>
      <el-table-column prop="guildId" label="我方公会ID" align="center"></el-table-column>
      <el-table-column prop="otherGuildId" label="对方公会ID" align="center"></el-table-column>
      <el-table-column prop="relationType" label="关系类型" align="center">
        <template #default="scope">
          {{ getRelationTypeText(scope.row.relationType) }}
        </template>
      </el-table-column>
      <el-table-column prop="relationTime" label="建立时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.relationTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空数据状态 -->
    <div v-if="totalRecords === 0 && !loading" class="empty-state">
      <el-empty description="暂无外交关系记录"></el-empty>
    </div>

    <div style="margin-top: 10px; display: flex; align-items: center;">
      <el-button type="primary" @click="showCreateDialog">添加外交关系</el-button>
      <el-button @click="resetPagination">查询所有外交关系</el-button>
      <el-input
          v-model="searchGuildId"
          placeholder="按我方公会ID筛选"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchDiplomaciesByGuildId"
      />
      <el-input
          v-model="searchOtherGuildId"
          placeholder="按对方公会ID筛选"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchDiplomaciesByOtherGuildId"
      />
    </div>

    <!-- 分页组件 -->
    <el-pagination
        v-if="totalRecords > 0"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecords"
    />

    <!-- 新增外交关系表单对话框 -->
    <el-dialog title="添加外交关系" v-model="dialogVisible" width="30%">
      <el-form :model="diplomacyForm" :rules="rules" ref="formRef">
        <el-form-item label="我方公会ID" prop="guildId">
          <el-input v-model.number="diplomacyForm.guildId" placeholder="请输入我方公会ID" />
        </el-form-item>
        <el-form-item label="对方公会ID" prop="otherGuildId">
          <el-input v-model.number="diplomacyForm.otherGuildId" placeholder="请输入对方公会ID" />
        </el-form-item>
        <el-form-item label="关系类型" prop="relationType">
          <el-select v-model="diplomacyForm.relationType" placeholder="请选择关系类型">
            <el-option label="同盟" value="ally"></el-option>
            <el-option label="敌对" value="enemy"></el-option>
            <el-option label="中立" value="neutral"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建立时间" prop="relationTime">
          <el-date-picker
              v-model="diplomacyForm.relationTime"
              type="datetime"
              placeholder="选择建立时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑外交关系对话框 -->
    <el-dialog title="编辑外交关系" v-model="editDialogVisible" width="30%">
      <el-form :model="editDiplomacyForm" :rules="rules" ref="editFormRef">
        <el-form-item label="我方公会ID">
          <el-input v-model.number="editDiplomacyForm.guildId" disabled />
        </el-form-item>
        <el-form-item label="对方公会ID" prop="otherGuildId">
          <el-input v-model.number="editDiplomacyForm.otherGuildId" />
        </el-form-item>
        <el-form-item label="关系类型" prop="relationType">
          <el-select v-model="editDiplomacyForm.relationType" placeholder="请选择关系类型">
            <el-option label="同盟" value="ally"></el-option>
            <el-option label="敌对" value="enemy"></el-option>
            <el-option label="中立" value="neutral"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建立时间" prop="relationTime">
          <el-date-picker
              v-model="editDiplomacyForm.relationTime"
              type="datetime"
              placeholder="选择建立时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateDiplomacy">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

// 从本地存储获取token
const getToken = () => localStorage.getItem('token') || '';

// 数据状态
const diplomacies = ref([]);
const loading = ref(false);
const searchGuildId = ref('');
const searchOtherGuildId = ref('');
const formRef = ref(null);
const editFormRef = ref(null);

// 分页状态
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

// 对话框状态
const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const isEdit = ref(false);

// 表单数据
const diplomacyForm = reactive({
  id: null,
  guildId: null,
  otherGuildId: null,
  relationType: 'neutral',
  relationTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
});

const editDiplomacyForm = reactive({
  id: null,
  guildId: null,
  otherGuildId: null,
  relationType: 'neutral',
  relationTime: null
});

// 表单验证规则
const rules = {
  guildId: [{ required: true, message: '请输入我方公会ID', trigger: 'blur' }],
  otherGuildId: [{ required: true, message: '请输入对方公会ID', trigger: 'blur' }],
  relationType: [{ required: true, message: '请选择关系类型', trigger: 'change' }],
  relationTime: [{ required: true, message: '请选择建立时间', trigger: 'change' }]
};

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '无记录';
  try {
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
  } catch (error) {
    return '格式错误';
  }
};

// 关系类型文本转换
const getRelationTypeText = (type) => {
  const types = {
    'ally': '同盟',
    'enemy': '敌对',
    'neutral': '中立'
  };
  return types[type] || type;
};

// 获取所有外交关系（带分页）
const fetchAllDiplomacies = async (page = currentPage.value, size = pageSize.value) => {
  try {
    loading.value = true;
    const params = {
      page,
      pageSize: size,
      sort: 'id',
      order: 'desc'
    };
    const response = await request.get('/guild/diplomacies', {
      params,
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200 && response.data && response.data.records) {
      diplomacies.value = response.data.records.map(diplomacy => ({
        ...diplomacy,
        relationTime: diplomacy.relationTime ? dayjs(diplomacy.relationTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      totalRecords.value = response.data.total;

      if (diplomacies.value.length === 0 && page > 1) {
        ElMessage.warning('当前页没有数据');
        currentPage.value = Math.max(1, page - 1);
        return fetchAllDiplomacies(currentPage.value, pageSize.value);
      } else if (diplomacies.value.length === 0) {
        ElMessage.info('暂无外交关系记录');
      } else {
        ElMessage.success('获取外交关系成功');
      }
    } else {
      diplomacies.value = [];
      totalRecords.value = 0;
      ElMessage.warning('获取外交关系失败');
    }
  } catch (error) {
    console.error('获取外交关系失败:', error);
    handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 根据我方公会ID获取外交关系（带分页）
const fetchDiplomaciesByGuildId = async () => {
  const guildId = searchGuildId.value.trim();
  if (!guildId) {
    ElMessage.warning('请输入我方公会ID');
    return;
  }

  // 重置分页到第一页
  currentPage.value = 1;

  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      sort: 'id',
      order: 'desc',
      guildId: guildId
    };
    const response = await request.get('/guild/diplomacies', {
      params,
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200 && response.data && response.data.records) {
      diplomacies.value = response.data.records.map(diplomacy => ({
        ...diplomacy,
        relationTime: diplomacy.relationTime ? dayjs(diplomacy.relationTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      totalRecords.value = response.data.total;

      if (diplomacies.value.length === 0) {
        ElMessage.info(`我方公会ID ${guildId} 没有外交关系记录`);
      } else {
        ElMessage.success(`获取我方公会ID为 ${guildId} 的外交关系成功`);
      }
    } else {
      diplomacies.value = [];
      totalRecords.value = 0;
      ElMessage.warning(`我方公会ID ${guildId} 没有外交关系记录`);
    }
  } catch (error) {
    console.error('获取外交关系失败:', error);
    handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 根据对方公会ID获取外交关系（带分页）
const fetchDiplomaciesByOtherGuildId = async () => {
  const otherGuildId = searchOtherGuildId.value.trim();
  if (!otherGuildId) {
    ElMessage.warning('请输入对方公会ID');
    return;
  }

  // 重置分页到第一页
  currentPage.value = 1;

  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      sort: 'id',
      order: 'desc',
      otherGuildId: otherGuildId
    };
    const response = await request.get('/guild/diplomacies', {
      params,
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200 && response.data && response.data.records) {
      diplomacies.value = response.data.records.map(diplomacy => ({
        ...diplomacy,
        relationTime: diplomacy.relationTime ? dayjs(diplomacy.relationTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      totalRecords.value = response.data.total;

      if (diplomacies.value.length === 0) {
        ElMessage.info(`对方公会ID ${otherGuildId} 没有外交关系记录`);
      } else {
        ElMessage.success(`获取对方公会ID为 ${otherGuildId} 的外交关系成功`);
      }
    } else {
      diplomacies.value = [];
      totalRecords.value = 0;
      ElMessage.warning(`对方公会ID ${otherGuildId} 没有外交关系记录`);
    }
  } catch (error) {
    console.error('获取外交关系失败:', error);
    handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 显示创建对话框
const showCreateDialog = () => {
  dialogVisible.value = true;
  isEdit.value = false;
  resetForm(diplomacyForm);

  nextTick(() => {
    const guildIdInput = document.querySelector('.guild-diplomacy-manage input[placeholder="请输入我方公会ID"]');
    if (guildIdInput) guildIdInput.focus();
  });
};

// 显示编辑对话框
const showEditDialog = (diplomacy) => {
  editDialogVisible.value = true;
  isEdit.value = true;

  editDiplomacyForm.id = diplomacy.id;
  editDiplomacyForm.guildId = diplomacy.guildId;
  editDiplomacyForm.otherGuildId = diplomacy.otherGuildId;
  editDiplomacyForm.relationType = diplomacy.relationType;
  editDiplomacyForm.relationTime = diplomacy.relationTime
      ? dayjs(diplomacy.relationTime).format('YYYY-MM-DD HH:mm:ss')
      : dayjs().format('YYYY-MM-DD HH:mm:ss');
};

// 重置表单数据
const resetForm = (form) => {
  form.id = null;
  form.guildId = null;
  form.otherGuildId = null;
  form.relationType = 'neutral';
  form.relationTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
};

// 统一处理API错误
const handleApiError = (error) => {
  if (error.response) {
    const { status, data } = error.response;
    if (status === 401) {
      ElMessage.error('未授权，请重新登录');
      setTimeout(() => {
        window.location.href = '/login';
      }, 2000);
    } else if (data && data.message) {
      ElMessage.error(data.message);
    } else {
      ElMessage.error(`请求失败: ${status} ${error.message}`);
    }
  } else {
    ElMessage.error('网络连接失败，请检查网络设置');
  }
};

// 提交添加外交关系表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    const response = await request.post('/guild/diplomacy', {
      ...diplomacyForm,
      relationTime: diplomacyForm.relationTime
    }, {
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200) {
      ElMessage.success('添加外交关系成功');
      dialogVisible.value = false;
      await fetchAllDiplomacies(currentPage.value, pageSize.value);
    } else {
      ElMessage.error(response.message || '添加外交关系失败');
    }
  } catch (error) {
    console.error('添加外交关系出错:', error);
    handleApiError(error);
  }
};

// 提交编辑外交关系表单
const updateDiplomacy = async () => {
  try {
    await editFormRef.value.validate();
    const response = await request.put('/guild/diplomacy', {
      ...editDiplomacyForm,
      relationTime: editDiplomacyForm.relationTime
    }, {
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200) {
      ElMessage.success('更新外交关系成功');
      editDialogVisible.value = false;
      await fetchAllDiplomacies(currentPage.value, pageSize.value);
    } else {
      ElMessage.error(response.message || '更新外交关系失败');
    }
  } catch (error) {
    console.error('更新外交关系出错:', error);
    handleApiError(error);
  }
};

// 删除外交关系
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要终止该外交关系吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await request.delete(`/guild/diplomacy/${id}`, {
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200) {
      ElMessage.success('终止外交关系成功');
      await fetchAllDiplomacies(currentPage.value, pageSize.value);
    } else {
      ElMessage.error(response.message || '终止外交关系失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('终止外交关系出错:', error);
      handleApiError(error);
    }
  }
};

// 重置分页到第一页
const resetPagination = () => {
  currentPage.value = 1;
  fetchAllDiplomacies();
};

// 每页数量改变时的处理
const handlePageSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  fetchAllDiplomacies(currentPage.value, pageSize.value);
};

// 当前页码改变时的处理
const handleCurrentPageChange = (newPage) => {
  currentPage.value = newPage;
  fetchAllDiplomacies(currentPage.value, pageSize.value);
};

onMounted(() => {
  // 检查登录状态
  if (!getToken()) {
    ElMessage.warning('请先登录');
    setTimeout(() => {
      window.location.href = '/login';
    }, 2000);
    return;
  }

  fetchAllDiplomacies();
});
</script>

<style scoped>
.guild-diplomacy-manage {
  padding: 20px;
}

.empty-state {
  margin-top: 20px;
  text-align: center;
}
</style>
}